// miniprogram/pages/restaurant/restaurant.js
import {
  $wuxLoading
} from '../../miniprogram_npm/wux-weapp/index'

var bmap = require('../../libs/bmap-wx.js')
var wxMarkerData = []
var app = getApp()

Page({

  /**
   * 页面的初始数据
   */
  data: {
    title: '当前位置',
    overall_rating: '', //评价
    price: '', //人均
    tel: '', //店铺电话
    shopAddr: '', //店铺地址
    markers: [],
    latitude: '',
    longitude: ''
  },

  buttonClick1: function () {
    var that = this
    that.getShopInfo(1)
  },

  buttonClick2: function () {
    var that = this
    that.getShopInfo(2)
  },

  buttonClick3: function () {
    var that = this
    that.getShopInfo(2)
  },

  getShopInfo: function (type) {
    var that = this

    that.$wuxLoading = $wuxLoading()
    that.$wuxLoading.show({
      text: '加载中...',
    })

    //每页店铺数
    var pagesize = 20

    //人均价位范围
    var priceSection
    //覆盖半径
    var radius

    if (type == 1) {
      priceSection = 'industry_type:cater|price_section:5,29'
      radius = 1000
    } else if (type == 2) {
      priceSection = 'industry_type:cater|price_section:30,1000'
      radius = 5000
    } else {
      priceSection = 'industry_type:cater'
      radius = 1000
    }

    var query = '美食'

    wx.request({
      url: 'https://api.map.baidu.com/place/v2/search',
      data: {
        query: query,
        scope: 2,
        filter: priceSection,
        coord_type: 2,
        page_size: pagesize,
        page_num: 0,
        output: 'json',
        ak: app.globalData.baiduAK,
        radius: radius,
        ret_coordtype: 'gcj02ll',
        location: app.globalData.latitude + ',' + app.globalData.longitude
      },
      header: {
        "content-type": "application/json"
      },
      method: 'GET',
      success(data) {
        // console.log(data)
        var res = data.data;
        if (res.status === 0) {

          //获取店铺总数
          var total = res.total
          if (total == 0) {
            that.setData({
              overall_rating: '附近没有符合的店铺'
            })
          } else {
            //假设有20个店铺,则1<=no<21
            var no = Math.floor(Math.random() * total) + 1
            //计算页数,向上取整
            var page = Math.ceil(no / pagesize)
            //计算在当前页第几位
            var pageNo = (no - (page - 1) * pagesize) == 0 ? pagesize : (no - (page - 1) * pagesize)

            // console.log(total)
            // console.log(no)
            // console.log(page)
            // console.log(pageNo)

            wx.request({
              url: 'https://api.map.baidu.com/place/v2/search',
              data: {
                query: query,
                scope: 2,
                filter: priceSection,
                coord_type: 2,
                page_size: pagesize,
                page_num: (page - 1),
                output: 'json',
                ak: app.globalData.baiduAK,
                radius: radius,
                ret_coordtype: 'gcj02ll',
                location: app.globalData.latitude + ',' + app.globalData.longitude
              },
              header: {
                "content-type": "application/json"
              },
              method: 'GET',
              success(data) {
                // console.log(data)
                if (data.data.status === 0) {
                  var results = data.data.results
                  // console.log(results)
                  // console.log(results[pageNo - 1])
                  var shopInfo = results[pageNo - 1]
                  var shopInfoDetail = shopInfo.detail_info

                  if (that.getEx(shopInfoDetail.tag)) {
                    var nextNo = 1; //下一个商品的序号,下标是nextNo-1
                    for (var i = 1; i <= results.length; i++) {
                      nextNo = pageNo + i
                      if (nextNo > results.length) {
                        nextNo -= results.length
                      }
                      //重新获取
                      shopInfo = results[nextNo - 1]
                      shopInfoDetail = shopInfo.detail_info
                      if (!that.getEx(shopInfoDetail.tag)) {
                        break;
                      }
                    }
                  }

                  // console.log(shopInfo)
                  // console.log(shopInfoDetail)
                  var overall_rating_temp
                  var price_temp
                  var tel_temp

                  if (shopInfoDetail.overall_rating == null || shopInfoDetail.overall_rating == '') {
                    overall_rating_temp = '没有评价'
                  } else {
                    overall_rating_temp = shopInfoDetail.overall_rating + '分'
                  }

                  if (shopInfoDetail.price == null || shopInfoDetail.price == '') {
                    price_temp = '未获取到'
                  } else {
                    price_temp = shopInfoDetail.price + '元'
                  }

                  if (shopInfo.telephone == null || shopInfo.telephone == '') {
                    tel_temp = '没有'
                  } else {
                    tel_temp = shopInfo.telephone
                  }

                  that.setData({
                    title: shopInfo.name,
                    overall_rating: '评价 : ' + overall_rating_temp,
                    price: '人均 : ' + price_temp,
                    tel: '联系方式 : ' + tel_temp,
                    shopAddr: '地点 : ' + shopInfo.address
                  })

                  let wxMarkerData = []
                  wxMarkerData[0] = {
                    id: 1,
                    latitude: shopInfo.location.lat,
                    longitude: shopInfo.location.lng,
                    title: shopInfo.name,
                    iconPath: '../../images/map/marker_red.png',
                    iconTapPath: '../../images/map/marker_red.png',
                    address: shopInfo.address,
                    telephone: shopInfo.telephone,
                    alpha: 1,
                    width: 20,
                    height: 20
                  }

                  that.setData({
                    markers: wxMarkerData,
                    latitude: shopInfo.location.lat,
                    longitude: shopInfo.location.lng
                  })
                }
              },
              fail(data) {
                console.log(data)
              },
              complete() {
                that.$wuxLoading.hide()
              }
            })
          }

        }
      },
      fail(data) {
        console.log(data)
      },
      complete() {
        that.$wuxLoading.hide()
      }
    })
  },

  getEx: function (tag) {
    var flag = false
    //判断tag是否含有不想要的店,比如"蛋糕", "咖啡", "茶座", "酒吧"
    var strEx = ["蛋糕", "咖啡", "茶座", "酒吧"]
    for (var i = 0; i < strEx.length; i++) {
      if ((tag).indexOf(strEx[i]) != -1) {
        flag = true
        break
      }
    }
    return flag
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    var that = this
    that.setData({
      markers: {},
      latitude: app.globalData.latitude,
      longitude: app.globalData.longitude
    })

    // 新建百度地图对象 
    var BMap = new bmap.BMapWX({
      ak: '***'
    });
    var fail = function (data) {
      console.log(data)
    };
    var success = function (data) {
      console.log(data)
      wxMarkerData = data.wxMarkerData;
      console.log(wxMarkerData)
      that.setData({
        markers: wxMarkerData
      });
      that.setData({
        latitude: wxMarkerData[0].latitude
      });
      that.setData({
        longitude: wxMarkerData[0].longitude
      });
    }
    // 发起POI检索请求 
    BMap.search({
      "query": '美食',
      "scope": 2,
      "filter": "industry_type:cater|price_section:5,29",
      "radius": 150,
      fail: fail,
      success: success,
      // 此处需要在相应路径放置图片文件 
      iconPath: '../../images/map/marker_red.png',
      // 此处需要在相应路径放置图片文件 
      iconTapPath: '../../images/map/marker_red.png'
    });

  //   query: query,
  //               scope: 2,
  //               filter: priceSection,
  //               coord_type: 2,
  //               page_size: pagesize,
  //               page_num: (page - 1),
  //               output: 'json',
  //               ak: app.globalData.baiduAK,
  //               radius: radius,
  //               ret_coordtype: 'gcj02ll',
  //               location: app.globalData.latitude + ',' + app.globalData.longitude
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})